import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// 商品项模型
class ItemModel extends ChangeNotifier {
  final int id;
  final String name;
  bool _isSelected = false;

  ItemModel({required this.id, required this.name});

  bool get isSelected => _isSelected;

  String get showName {
    return '$name ${_isSelected? '已选择' : '-'}';
  }

  void toggleSelection() {
    _isSelected = !_isSelected;
    notifyListeners(); // 通知监听者状态变化
  }
}

// 商品列表状态管理
class ItemListProvider extends ChangeNotifier {
  final List<ItemModel> _items = [];
  ItemModel? _selectedItem;

  List<ItemModel> get items => _items;
  ItemModel? get selectedItem => _selectedItem;

  // 初始化商品数据
  void initItems(int count) {
    _items.clear();
    for (int i = 1; i <= count; i++) {
      _items.add(ItemModel(id: i, name: '商品 $i'));
    }
    _selectedItem = _items[0];
    notifyListeners();
  }

  // 选择商品
  void selectItem(ItemModel item) {
    // 先取消之前的选择
    print('---取消: ${_selectedItem?.id}');
    if (_selectedItem != null) {
      _selectedItem!._isSelected = false;
      _selectedItem!.notifyListeners();
    }

    // 再选择新项
    item._isSelected = true;
    _selectedItem = item;
    print('---选择: ${item.id}');
    _selectedItem!.notifyListeners();
    // 不需要调用 notifyListeners()，因为 ItemModel 自己会通知
    // notifyListeners();
  }
}

// 商品项组件
class ItemWidget extends StatelessWidget {
  final ItemModel item;

  const ItemWidget({Key? key, required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 使用 Consumer 监听当前商品的状态变化
    return Consumer<ItemModel>(
      builder: (context, model, child) {
        print('商品 ${model.id} 刷新了 ${model.isSelected}'); // 测试刷新情况

        return ListTile(
          title: Text(model.showName),
          trailing: model.isSelected ? const Icon(Icons.check) : null,
          tileColor: model.isSelected ? Colors.blue.withOpacity(0.1) : null,
          onTap: () {
            // 更新选中状态
            context.read<ItemListProvider>().selectItem(model);
          },
        );
      },
    );
  }
}

// 主页面
class SelectableListPage extends StatelessWidget {
  const SelectableListPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 初始化数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ItemListProvider>().initItems(20);
    });

    return Scaffold(
      appBar: AppBar(title: const Text('局部刷新示例')),
      body: Consumer<ItemListProvider>(
        builder: (context, provider, child) {
          return ListView.builder(
            itemCount: provider.items.length,
            itemBuilder: (context, index) {
              final item = provider.items[index];

              // 为每个商品创建单独的 ChangeNotifierProvider
              return ChangeNotifierProvider.value(
                value: item,
                child: ItemWidget(item: item),
              );
            },
          );
        },
      ),
    );
  }
}

// 应用入口
// void main() {
//   runApp(
//     MultiProvider(
//       providers: [
//         ChangeNotifierProvider(create: (_) => ItemListProvider()),
//       ],
//       child: const MyApp(),
//     ),
//   );
// }

// class MyApp extends StatelessWidget {
//   const MyApp({Key? key}) : super(key: key);
//
//   @override
//   Widget build(BuildContext context) {
//     return MaterialApp(
//       title: 'Flutter 局部刷新 Demo',
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//       ),
//       home: const SelectableListPage(),
//     );
//   }
// }